import { defineStore } from 'pinia'
import { foodApi } from '../services/api'

export const useFoodStore = defineStore('food', {
    state: () => ({
        foods: []
    }),
    
    actions: {
        // 获取所有食物
        async fetchFoods() {
            try {
                const response = await foodApi.getAllFoods()
                this.foods = response.data
            } catch (error) {
                console.error('获取食物列表失败:', error)
                throw error
            }
        },
        
        // 获取随机食物
        async getRandomFood(category) {
            try {
                let foods
                if (category) {
                    const response = await foodApi.getFoodsByCategory(category)
                    foods = response.data
                } else {
                    foods = this.foods
                }
                
                if (foods.length === 0) return null
                const randomIndex = Math.floor(Math.random() * foods.length)
                return foods[randomIndex]
            } catch (error) {
                console.error('获取随机食物失败:', error)
                throw error
            }
        },
        
        // 添加食物
        async addFood(foodData) {
            try {
                const response = await foodApi.addFood(foodData)
                this.foods.push(response.data)
            } catch (error) {
                console.error('添加食物失败:', error)
                throw error
            }
        },
        
        // 更新食物
        async updateFood(id, foodData) {
            try {
                const response = await foodApi.updateFood(id, foodData)
                const index = this.foods.findIndex(food => food.id === id)
                if (index !== -1) {
                    this.foods[index] = response.data
                }
            } catch (error) {
                console.error('更新食物失败:', error)
                throw error
            }
        },
        
        // 删除食物
        async deleteFood(id) {
            try {
                await foodApi.deleteFood(id)
                const index = this.foods.findIndex(food => food.id === id)
                if (index !== -1) {
                    this.foods.splice(index, 1)
                }
            } catch (error) {
                console.error('删除食物失败:', error)
                throw error
            }
        }
    }
})